package com.xmy.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.study.entity.*;
import com.xmy.study.service.*;
import com.xmy.study.util.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 * 帐号 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2023-09-08
 */
@RestController
@RequestMapping("/api/admin/studentAccount")
public class StudentAccountController {
    @Autowired
    IStudentAccountService iStudentAccountService;

    @Autowired
    IEduClassTypeService iEduClassTypeService;

    @Autowired
    IStudentService iStudentService;

    @Autowired
    IChaPlanService iChaPlanService;

    @Autowired
    IMqPushService iMqPushService;


    @Autowired
    IdWorker idWorker;

    @Value("${subjectsId}")
    String SUBJECTS_IDS;

    @GetMapping("")
    @ApiOperation("帐号列表")
    public Result searchAccount(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<StudentAccount> iPage = new Page<>(pageNum, pageSize);

        String studentName = (String) reMap.get("studentName");
        String account = (String) reMap.get("account");
        String status = (String) reMap.get("status");
        String accountType = (String) reMap.get("accountType");
        String yearClassId = (String) reMap.get("yearClassId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String schoolId = (String) reMap.get("schoolId");

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(studentName), "student_name", StringUtils.toStringTrim(studentName));
        queryWrapper.eq(StringUtils.isNotBlank(account), "account", account);
        queryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
        queryWrapper.eq(StringUtils.isNotBlank(accountType), "account_type", accountType);
        queryWrapper.eq(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        queryWrapper.orderByDesc("id");

        iStudentAccountService.page(iPage, queryWrapper);

        // 在循环外创建缓存
        Map<Long, String> classTypeCache = new HashMap<>();

        for (StudentAccount studentAccount : iPage.getRecords()) {
            studentAccount.setYearClassStr(CommonUtil.getYearClassNameForId(studentAccount.getYearClassId()));
            if (studentAccount.getClassTypeId() != null) {
                //班型中文名
                if (!classTypeCache.containsKey(studentAccount.getClassTypeId())) {
                    classTypeCache.put(studentAccount.getClassTypeId(), iEduClassTypeService.getById(studentAccount.getClassTypeId()).getName());
                }
                studentAccount.setClassTypeStr(classTypeCache.get(studentAccount.getClassTypeId()));
            }
        }

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    @PostMapping("")
    @ApiOperation("账号添加/修改")
    public Result saveAccount(@RequestBody StudentAccount studentAccount) {
        if (studentAccount.getId() != null) {
            StudentAccount account = iStudentAccountService.getById(studentAccount.getId());
            if (Objects.isNull(account)) {
                return new Result(Code.EXP_ERROR, null, "该账号不存在");
            } else {
                //培优转提高班
                if (account.getClassTypeId().equals(1565023758494502914L) && studentAccount.getClassTypeId().equals(1575859909042028546L)){
                    UpdateWrapper<ChaPlan> chaPlanUpdateWrapper = new UpdateWrapper<>();
                    chaPlanUpdateWrapper.eq("year_part",studentAccount.getYearPart());
                    chaPlanUpdateWrapper.eq("quarter_num",studentAccount.getQuarterNum());
                    chaPlanUpdateWrapper.eq("class_type_id",1565023758494502914L);
                    //chaPlanUpdateWrapper.eq("course_version_id",account.getClassTypeId());
                    chaPlanUpdateWrapper.eq("subjects_id",this.SUBJECTS_IDS);//数学
                    chaPlanUpdateWrapper.eq("student_id",account.getStudentId());
                    chaPlanUpdateWrapper.set("class_type_id",1575859909042028546L);
                    studentAccount.setBeforeClassTypeId(account.getClassTypeId());
                    iChaPlanService.update(chaPlanUpdateWrapper);
                }else if (account.getClassTypeId().equals(1575859909042028546L) && studentAccount.getClassTypeId().equals(1565023758494501025L)){
                    //提高转基础
                    UpdateWrapper<ChaPlan> chaPlanUpdateWrapper = new UpdateWrapper<>();
                    chaPlanUpdateWrapper.eq("year_part",studentAccount.getYearPart());
                    chaPlanUpdateWrapper.eq("quarter_num",studentAccount.getQuarterNum());
                    chaPlanUpdateWrapper.eq("class_type_id",1575859909042028546L);
                    //chaPlanUpdateWrapper.eq("course_version_id",account.getClassTypeId());
                    chaPlanUpdateWrapper.eq("subjects_id",this.SUBJECTS_IDS);//数学
                    chaPlanUpdateWrapper.eq("student_id",account.getStudentId());
                    chaPlanUpdateWrapper.set("class_type_id",1565023758494501025L);
                    studentAccount.setBeforeClassTypeId(account.getClassTypeId());
                    iChaPlanService.update(chaPlanUpdateWrapper);
                }
                /*else if (studentAccount.getClassTypeId().equals(1575859909042028546L) && account.getClassTypeId().equals(1565023758494501025L)){
//                    if (studentAccount.getBeforeClassTypeId().equals(1575859909042028546L)){
//                    }
                        //基础班转提高
                        UpdateWrapper<ChaPlan> chaPlanUpdateWrapper = new UpdateWrapper<>();
                        chaPlanUpdateWrapper.eq("year_part",studentAccount.getYearPart());
                        chaPlanUpdateWrapper.eq("quarter_num",studentAccount.getQuarterNum());
                        chaPlanUpdateWrapper.eq("class_type_id",1565023758494501025L);
                        //chaPlanUpdateWrapper.eq("course_version_id",account.getClassTypeId());
                        chaPlanUpdateWrapper.eq("subjects_id",2);//数学
                        chaPlanUpdateWrapper.eq("student_id",account.getStudentId());
                        chaPlanUpdateWrapper.set("class_type_id",1575859909042028546L);
                        iChaPlanService.update(chaPlanUpdateWrapper);
                }*/

                iStudentAccountService.updateById(studentAccount);

                PerStudentClassType perStudentClassType = new PerStudentClassType();
                perStudentClassType.setStudentId(account.getStudentId());
                perStudentClassType.setClassTypeId(studentAccount.getClassTypeId());
                perStudentClassType.setSubjectsId(Long.parseLong(this.SUBJECTS_IDS));
                iMqPushService.updateStudentGradeClassTypeId(perStudentClassType);

                Student student = iStudentService.getById(account.getStudentId());
                if (!Objects.isNull(student)){
                    student.setName(studentAccount.getStudentName());
                    iStudentService.updateById(student);
                }
            }

        } else {
            Long studentId = idWorker.nextId();

            if (StringUtils.isBlank(studentAccount.getAccount())) {
                //去除前后两端空格
                String studentName = StringUtils.toStringTrim(studentAccount.getStudentName());
                studentAccount.setStudentName(studentName);
                //账号密码：获取学生姓名拼音+后四位随机数
                String account = CommonUtil.getPingyinForChinese(studentName);
                studentAccount.setAccount(account);
                studentAccount.setPwd(account);
            }

            studentAccount.setId(idWorker.nextId());
            studentAccount.setStudentId(studentId);
            iStudentAccountService.save(studentAccount);

            Student student = new Student();
            student.setId(studentId);
            student.setName(studentAccount.getStudentName());
            iStudentService.save(student);
        }

        return new Result(Code.OK, null, Code.OK_MSG);
    }

    @DeleteMapping("")
    @ApiOperation("账号删除")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String")
    public Result removeAccount(@RequestParam String id) {
        StudentAccount account = iStudentAccountService.getById(id);
        if (Objects.isNull(account)) {
            return new Result(Code.EXP_ERROR, null, "该账号不存在");
        }
        iStudentAccountService.removeById(id);
        iStudentService.removeById(account.getStudentId());
        return new Result(Code.OK, null, Code.DELETE_OK_MSG);
    }


    @GetMapping("/excel")
    @ApiOperation("帐号列表导出")
    public Result searchAccountExcel(@RequestParam Map reMap) throws IOException {
        String name = (String) reMap.get("name");
        String account = (String) reMap.get("account");
        String status = (String) reMap.get("status");
        String accountType = (String) reMap.get("accountType");
        String yearClassId = (String) reMap.get("yearClassId");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");

        QueryWrapper<StudentAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name), "student_name", StringUtils.toStringTrim(name));
        queryWrapper.eq(StringUtils.isNotBlank(account), "account", account);
        queryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
        queryWrapper.eq(StringUtils.isNotBlank(accountType), "account_type", accountType);
        queryWrapper.eq(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);

        List<StudentAccount> studentAccounts = iStudentAccountService.list(queryWrapper);

//        for (StudentAccount studentAccount : studentAccounts) {
//            studentAccount.setYearClassStr(CommonUtil.getYearClassNameForId(studentAccount.getYearClassId()));
//            studentAccount.setClassTypeStr(iEduClassTypeService.getOne(new QueryWrapper<EduClassType>().eq("id", studentAccount.getClassTypeId())).getName());
//        }

//        ExcelExportHandle.export(response, "学员账号", studentAccounts, StudentAccount.class);

        /*Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建顶部样式
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        List<String> headList = new ArrayList<>();
        headList.add("姓名");
        headList.add("账号");
        headList.add("密码");
        headList.add("年级");
        headList.add("班型");

        // 写入表头
        int columnCount = headList.size();

        for (int i = 0; i < columnCount; i++) {
            Row headerRow = sheet.createRow(0);
            for (int j = 0; j < headList.size(); j++) {
                Cell headerCell = headerRow.createCell(j);
                headerCell.setCellValue(headList.get(j));
                headerCell.setCellStyle(cellStyle); // 设置单元格样式
            }
        }

        // 创建顶部样式
        CellStyle cellStyle1 = workbook.createCellStyle();
        Font font1 = workbook.createFont();
        font1.setFontHeightInPoints((short) 11);
        cellStyle1.setFont(font1);
        cellStyle1.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        // 写入数据行
        int rowNum = 1;
        for (StudentAccount studentAccount : studentAccounts) {
            Row row = sheet.createRow(rowNum++);
            Cell cell3 = row.createCell(0);
            cell3.setCellValue(studentAccount.getStudentName());
            sheet.setColumnWidth(0, 20 * 256);
            cell3.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell4 = row.createCell(1);
            cell4.setCellValue(studentAccount.getAccount());
            sheet.setColumnWidth(1, 20 * 256);
            cell4.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell5 = row.createCell(2);
            cell5.setCellValue(studentAccount.getPwd());
            sheet.setColumnWidth(2, 20 * 256);
            cell5.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell6 = row.createCell(3);
            cell6.setCellValue(studentAccount.getYearClassStr());
            sheet.setColumnWidth(3, 20 * 256);
            cell6.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell7 = row.createCell(4);
            cell7.setCellValue(studentAccount.getClassTypeStr());
            sheet.setColumnWidth(4, 20 * 256);
            cell7.setCellStyle(cellStyle1); // 设置单元格样式
        }


        String fileName = "学员账号" + ".xls";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();*/

        return new Result(Code.OK, studentAccounts, "导出成功");

    }


}
